package com.sks.web.action.news;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.stereotype.Controller;

import com.sks.bean.QueryResult;
import com.sks.bean.pojo.AuditHistory;
import com.sks.bean.pojo.Feature;
import com.sks.bean.pojo.News;
import com.sks.bean.privilege.Employee;
import com.sks.bean.privilege.SystemPrivilege;
import com.sks.core.SystemConstants;
import com.sks.service.house.AuditHistoryService;
import com.sks.service.news.FeatureService;
import com.sks.service.news.NewsService;
import com.sks.service.privilege.EmployeeService;
import com.sks.utils.SiteUrl;
import com.sks.utils.WebUtil;
import com.sks.web.action.BasicAction;
import com.sks.web.action.privilege.Permission;
import com.sks.web.formbean.news.NewsForm;


/**
 * 新闻编辑等功能
 * @author yuanjiayuan
 *
 */
@Controller("/cms/news/newsManage")
public class NewsManageAction extends BasicAction{
	
	@Resource(name="newsServiceBean")private NewsService newsService;
	
	@Resource(name = "featureServiceBean")private FeatureService featureService;
	
	@Resource(name = "employeeServiceBean")private EmployeeService employeeService;
	
	@Resource(name = "auditHistoryServiceBean") private AuditHistoryService ahService;
	
	/**
	 * 验证public ActionForward add(ActionMapping, ActionForm, HttpServletRequest,
	 * HttpServletResponse)方法 如果存在同名的新闻名称，则返回错误信息
	 * */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void beforeadd(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionMessages errors = new ActionMessages();
		getFeatures(request);
		NewsForm formbean = (NewsForm) form;
		List params = new ArrayList();
		params.add(formbean.getTitle());
		StringBuffer jpql = new StringBuffer("o.title = ?" + params.size());
		if (EDIT.equals(formbean.getMethod())) {
			params.add(formbean.getNewsId());
			jpql.append(" and o.newsId <> ?" + params.size());
		}
		QueryResult<News> m = newsService.getScrollData(-1, -1, jpql.toString(),
				params.toArray());
		if (null != m && m.getResultlist().size() > 0) {
			// 提示信息
			errors.add("name", new ActionMessage("新闻名称不能重复", false));
			request.setAttribute(ACTION, formbean.getMethod());
		}
		saveErrors(request, errors);
	}
	
	/**
	 * 跳转到添加新闻页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_UPDATE)
	public ActionForward addUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		getFeatures(request);
		getEmployee(request);
		request.setAttribute("news", newsService.getScrollData().getResultlist());
		return mapping.findForward("add");
		
	}
	
	/***
	 * 添加新闻
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_UPDATE)
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {	
		NewsForm formbean = (NewsForm)form;
		
		News news = new News();
		Date date = new Date();
		copyProperties(formbean, news);
		Feature feature = featureService.find(formbean.getFeatureId());//专题
		news.setFeature(feature);
		Employee employee = employeeService.find(WebUtil.getEmployee(request).getUsername());
		news.setCreateEmployee(employee);
		
		news.setStatus(News.NEWS_STATUS_NONE_PUBLISH);
		news.setCreateUserId(employee.getUsername());
		news.setLastUpdateUserId(employee.getUsername());
		news.setFeatureId(feature.getFeatureId());
		news.setCreateTime(date);
		news.setLastUpdateTime(date);
		news.setClick(0);//初始化点击次数
		if(formbean.getContent().length() < 200){
			news.setSection(formbean.getContent().replaceAll("<[^>]*>","").substring(0, formbean.getContent().length()));
		}else {
			news.setSection(formbean.getContent().replaceAll("<[^>]*>","").substring(0, 200));
		}
		news.setNewsId(null);
		newsService.save(news);
		request.setAttribute(MESSAGE, "新闻添加成功");		
		request.setAttribute("urladdress", SiteUrl.readUrl("cms.news.list"));
		return mapping.findForward(MESSAGE);
	}
	
	/***
	 * 修改界面之前验证
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void beforeedit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		NewsForm formbean = (NewsForm) form;
		this.beforeadd(mapping, formbean, request, response);
	}
	
	/***
	 * 编辑新闻
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_VIEW)
	public ActionForward editUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		this.saveToken(request);
		
		getFeatures(request);
		getEmployee(request);
        NewsForm formbean = (NewsForm) form;
		News news = newsService.find(formbean.getNewsId());
		copyProperties(news, formbean);
		
		if (News.NEWS_STATUS_PUBLISHED.equals(news.getStatus())) {//只有在未发布的状态下才能修改楼盘
			SimpleDateFormat publishTime =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			formbean.setPublishTime(publishTime.format(news.getPublishTime()));//转为字符串类型
		}
		
		
		if (News.NEWS_STATUS_NONE_PUBLISH.equals(news.getStatus())) {//只有在未发布的状态下才能修改楼盘
			this.setReadOnly(request, "editUI");
		} else {
			request.setAttribute(SystemConstants.SYS_IS_READ_ONLY, true);
		}
		request.setAttribute(SystemConstants.SYS_CAN_AUDIT,
				WebUtil.hasPermission(request, SystemPrivilege.MODULE_NAME_NEWS, SystemPrivilege.PRIVILEGE_NAME_AUDIT));
		
		request.setAttribute(ACTION, EDIT);
		return mapping.findForward(EDIT);
	}
	
	/***
	 * 修改新闻
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_UPDATE)
	public ActionForward edit(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
		throws Exception {
		NewsForm formbean = (NewsForm)form;
		News news = new News();
		Date date = new Date();
		
		copyProperties(formbean, news);
		Feature feature = featureService.find(formbean.getFeatureId());
		Employee employee = employeeService.find(WebUtil.getEmployee(request).getUsername());
		news.setCreateEmployee(employee);
		news.setFeature(feature);
		news.setFeatureId(feature.getFeatureId());
		news.setCreateUserId(employee.getUsername());//最后修改者
		
		news.setCreateTime(newsService.find(formbean.getNewsId()).getCreateTime());
		news.setLastUpdateTime(date);
		if(formbean.getContent().length() < 200){
			news.setSection(formbean.getContent());
		}else {
			news.setSection(formbean.getContent().replaceAll("<[^>]*>","").substring(0, 200));
		}
		 newsService.update(news);
		 request.setAttribute(MESSAGE, "修改新闻成功");
		 request.setAttribute("urladdress", SiteUrl
			.readUrl("cms.news.list"));
		 return mapping.findForward(MESSAGE);
	}

	/***
	 * 删除新闻
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_UPDATE)
	public ActionForward delete(ActionMapping mapping, ActionForm form,
				HttpServletRequest request, HttpServletResponse response)
				throws Exception {
			NewsForm formbean = (NewsForm) form;
			newsService.delete(formbean.getNewsId());
			request.setAttribute(MESSAGE, "删除新闻成功");
			request.setAttribute("urladdress", SiteUrl
					.readUrl("cms.news.list"));
			return mapping.findForward(MESSAGE);
		}
	
	/***
	 * 查询新闻
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_VIEW)
	public ActionForward queryUI(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		return mapping.findForward(QUERY);
	}
	
	private void getFeatures(HttpServletRequest request) {
		QueryResult<Feature> features = featureService.getScrollData(-1, -1);
		request.setAttribute("features", features.getResultlist());
	}
	
	private void getEmployee(HttpServletRequest request) {
		QueryResult<Employee> features = employeeService.getScrollData(-1, -1);
		request.setAttribute("createEmployee", features.getResultlist());
	}
	
	@Permission(module = SystemPrivilege.MODULE_NAME_NEWS, privilege = SystemPrivilege.PRIVILEGE_NAME_AUDIT)
	public ActionForward changeStatus(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		NewsForm formbean = (NewsForm) form;
		News news = newsService.find(formbean.getNewsId());
		if (null != news) {
			String oldStatus = news.getStatus();
			String newStatus = formbean.getStatus();
			Date date = new Date();
			
			if (News.NEWS_STATUS_NONE_PUBLISH.equals(oldStatus)) {//未发布
				if (News.NEWS_STATUS_PUBLISHED.equals(newStatus)) {//已发布
					news.setStatus(News.NEWS_STATUS_PUBLISHED);
					news.setPublishTime(date);
				}
			} else if (News.NEWS_STATUS_PUBLISHED.equals(oldStatus)) {//已发布
				if (News.NEWS_STATUS_NONE_PUBLISH.equals(newStatus)) {//撤销发布
					news.setStatus(News.NEWS_STATUS_NONE_PUBLISH);
					news.setPublishTime(null);
				} else if (News.NEWS_STATUS_INVALIDATE.equals(newStatus)) {//发布->下架
					news.setStatus(News.NEWS_STATUS_INVALIDATE);
					
				}
			} else if (News.NEWS_STATUS_INVALIDATE.equals(oldStatus)) {//已下架
				if (News.NEWS_STATUS_NONE_PUBLISH.equals(newStatus)) {//撤销下架返回未发布状态
					news.setStatus(News.NEWS_STATUS_NONE_PUBLISH);
					
				} else if (News.NEWS_STATUS_PUBLISHED.equals(newStatus)) {//撤销下架返回已发布状态
					news.setStatus(News.NEWS_STATUS_PUBLISHED);
					news.setPublishTime(date);
				}
			}
			newsService.update(news);
			
			Employee emp = WebUtil.getEmployee(request);
			emp = employeeService.find(emp.getUsername());
			AuditHistory ah = new AuditHistory(emp, AuditHistory.OBJ_TYPE_NEWS, news.getNewsId(), date, oldStatus, newStatus);
			ahService.save(ah);
		}
		return editUI(mapping, form, request, response);
	}
}
